/**
 * jQuery Plugin Of CMTI
 * version: 0.1 (2012-07-10)
 * version: 0.2 (2012-07-27)
 * Developer: Zheyuan Zhang
 * 
 */


/**
 * The first plugin. 
 * This plugin is the method for image upload. 
 * You can initialize the input element into the imageUpload widget.
 * version: 0.1 (2012-07-10)
 */
(function($){// start closure
    
    var $current,
    $dialog,
    $frame ;
    $dialog = $('#uploadDialog');
    $frame = $('#uploadFrame');
    //the initial method
    function init(target,opts){//初始化
        
        var $this,
        $box ,  //the box encase widget.
        $upload,    //the button which open the dialog of upload. 
        $view,      //the butto which preview the images.
        $images,    //the box store images.
        $imgNum,    //show how many images.
        $cuis,
        $form,
        btnAndView ;
        
        btnAndView= '';
        $this = $(target);
        
        $form = $this.closest('form');
        $cuis = $form.children('.iuCurrentImages');
        if($cuis.length<1){//如果当前form中隐藏域不存在则添加
            $form.append('<input class="iuCurrentImages" name="'+opts.currentImageName+'" type="hidden" />');
            $cuis = $form.children('.iuCurrentImages');
        }
        $this.data('ifInitImUp',true);//是否已经初始化
        $this.data('previewUrl',opts.previewUrl);//预览地址
       
        btnAndView += '<a href="Javascript:void(0)" class="upload-btn" >上传</a>';
        btnAndView += '<a href="Javascript:void(0)" class="img-view" title="预览" >0</a>';
        btnAndView += '<div class="images-box" style="display: none"></div>';
        $this.addClass('hidden-img-value').wrap('<div class="image-upload" />').parent().prepend(btnAndView).end()
        .focus(function(){
            $this.blur();
        })
        .css({
            'color' : opts.valueInputColor,
            'background-color' : opts.valueInputColor
        })
        .validatebox({
            required:opts.required,
            missingMessage:opts.validMsg
        });
        
        $box = $this.parent();
        $upload = $('a.upload-btn',$box);
        $view = $('a.img-view',$box);
        $images = $('div.images-box',$box);
        
        //initialize the button into easyui's linkbutton.
        $upload.linkbutton({
            iconCls:'icon-pic-add' ,
            plain:true
        });
        $view.linkbutton({
            iconCls:'icon-images-view' ,
            plain:true
        });
        
        $imgNum = $view.find("span.l-btn-text");
        
        $upload.click(function(e){//点击上传按钮时的动作
            if(opts.maxImageNum!=null  && $imgNum.text() >= opts.maxImageNum ){//图片超出则提示
                $.messager.alert('系统提示','最多只能上传'+opts.maxImageNum+'张图片，无法继续上传！','warning');
                return false;
            }
            if($this!==$current){//当前点击的元素是否和上一次一样，不一样则销毁重置
                $current = $this;
                if($dialog.length>0){
                    $dialog.dialog('destroy');
                }
                $('body').append('<div id="uploadDialog" ><iframe name="uploadFrame" id="uploadFrame" style="width:100%;height:98%;" scrolling="no" frameborder="0" allowtransparency="true" src="'+opts.uploadFrameUrl+'"></iframe></div>');
            
                $dialog = $('#uploadDialog');
                $frame = $('#uploadFrame');
                
                $dialog.dialog({
                    title:"图片上传",
                    iconCls:"icon-trow",
                    closed:true,
                    width:575,
                    height:430,
                    modal:true,
                    buttons:[{
                        text:'确定',
                        handler:function(){
                            //put the images into the $images,and change the view of $imgNum.
                            $images.append($frame.contents().find("#imagesBox").html());
                            parseImage();
                            setIuCurrentImages($cuis,$form);
                            $dialog.dialog('close');
                        }
                    },{
                        text:'取消',
                        handler:function(){
                            $dialog.dialog('close');
                        }
                    }],
                    onBeforeClose:function(){
                        //reload the upload flash
                        $frame.get(0).contentWindow.location.reload(true);
                        //valid 
                        $this.validatebox('isValid');
                        opts.onBeforeDialogClose.call(this,$this);
                    },
                    onBeforeOpen:function(){
                        $(".validatebox-tip").hide();
                        opts.onBeforeDialogOpen.call(this,$this);
                    //                        $(".validatebox-tip").hide();
                    //                $images.children('a.readyImg').removeClass("fancybox");
                    },
                    onClose: function(){
                        opts.onDialogClose.call(this,$this);
                    },
                    onOpen: function(){
                        opts.onDialogOpen.call(this,$this);
                    }    
                });
            }
            
            $dialog.dialog('open');
        });
         
        $view.click(function(){//当预览按钮点击时
            $('.fancybox').fancybox({
                prevEffect : 'fade',
                nextEffect : 'fade',
                removeUrl  : opts.removeUrl,
                beforeShow : function() {
                    $(".validatebox-tip").hide();
                    this.title = '图片 ' + (this.index + 1) + ' / ' + this.group.length + (this.title ? ' - ' + this.title : '');
                    opts.beforeViewShow.call(this,$this);
                    if($this.data('currentAction')=='readOnly'){//如果是只读，则隐藏删除按钮
                        this.removeBtn= false;
                    }else{
                        this.removeBtn= true;
                    }
                },
                beforeClose:function(){
                    opts.beforeViewClose.call(this,$this);
                },
                afterClose:function() {
                    $(".fancybox").removeClass("fancybox");
                    setIuCurrentImages($cuis,$form);
                    $this.validatebox('isValid');
                    opts.afterViewClose.call(this,$this);
                },
                onRemove:function(){
                    parseImage();
                    opts.onRemove.call(this,$this);
                }
            });
            if($images.children("a:first").length>0){//有图片则预览，无则提示
                $images.children('a.ready-img').addClass("fancybox").first().click();
            }else{
                $.messager.alert("友情提示", "无图片上传", 'warning');
            }
        });
        
        function parseImage(){
            $imgNum.text($images.children('a').length);
            $this.val(setImgValue($images.children('a.ready-img')));
        }
    }    
    //set value
    function setImgValue(elements){//向元素添加值
        var imgNm,title,arr;
        imgNm = [];
        title = '';
        arr = [];
        elements.each(function(i,v){
            title = $(v).attr('title');
            arr = $(v).children('img').attr('src').split('/');
            imgNm.push(title + ':' +arr[arr.length-1]);
        });
        return imgNm.join(',');
    }
    
    function setIuCurrentImages($cuis,$form){//向隐藏域中添加值
        var curImg;
        var arr = new Array();
        $('a.ready-img',$form.find('.images-box')).each(function(i,v){
            curImg = $(v).children('img').attr('src').split('/');
            arr[i] = curImg[curImg.length-1] ;
        });
        $cuis.val(arr.join(','));
    }
            
    $.fn.imageUpload = function(options, param){
        if (typeof options === 'string'){//如果是调用方法，则执行
            return $.fn.imageUpload.methods[options](this, param);
        }
        
        var opts = $.extend({}, $.fn.imageUpload.defaults, options);
        this.each(function(){
            if(!$(this).data('ifInitImUp')){
                init(this,opts);
                $(this).data('ifInitImUp',true);
            }
        });
        
        return this;
    };
    
    $.fn.imageUpload.methods = {//所有方法
        isValid: function(jq){//立即执行验证
            var flag = true;
            jq.each(function(){
                flag = $(this).validatebox('isValid') && flag;
            });
            return flag ;
        },
        invalid: function(jq){//移除验证
            jq.each(function(){
                $(this).validatebox({
                    required:false
                });
            });
            return jq;
        },
        envalid: function(jq){//添加验证
            jq.each(function(){
                $(this).validatebox({
                    required:true
                });
            });
            return jq;
        },
        backFill: function(jq){//回填图片
            var arr ,content,info,val;
            jq.each(function(i,e){
                var $this = $(this);
                var $parent = $this.parent();
                var previewUrl = '';
                previewUrl = $this.data('previewUrl');
                arr = [];
                val = $.trim($this.val());
                if(val.length>0){
                    arr = val.split(',');
                }
                content = '';
                for(var i = 0;i<arr.length;i++){
                    info = arr[i].split(':');
                    content += '<a class="ready-img" title="'+info[0]+'" data-fancybox-group="gallery" href="'+previewUrl+'/uploadFiles/images/'+info[1]+'"><img src="'+previewUrl+'/uploadFiles/images/'+info[1]+'" alt=""></a>'
                }
                $parent.children(".images-box").empty().append(content);
                $parent.children(".img-view").find(".l-btn-text").text( $parent.children(".images-box").children('a').length);
            });
            return jq;
        },
        readOnly: function(jq){//只读显示，即没有上传按钮和预览时的删除按钮
            jq.each(function(){
                var $this = $(this);
                $this.data('currentAction','readOnly');
                $this.validatebox({
                    required:false
                });
                $this.parent().children('a.upload-btn').hide();
            });
            return jq;
        },
        edit: function(jq){//重新显示上传按钮和预览时的删除按钮
            jq.each(function(){
                var $this = $(this);
                $this.data('currentAction','edit');
                $this.parent().children('a.upload-btn').show();
            });
            return jq;
        },
        clear: function(jq){//清空预览时的图片和数字清0
            jq.each(function(){
                var $this = $(this);
                var $parent = $this.parent();
                $parent.children(".images-box").empty();
                $parent.children(".img-view").find(".l-btn-text").text(0);
            });
            return jq;
        }
    }
    
    $.fn.imageUpload.defaults = {//默认配置
        uploadFrameUrl:'/ueditor/dialogs/image/imagesUpload.jsp', //图片上传的frame的url
        previewUrl:'', //图片预览的url
        removeUrl:'', //移除图片时调用的url，如果为空，则无需调用
        removingImageName:'removingImage',//删除的图片的名字
        valueInputColor: 'white', //验证框的颜色
        currentImageName: 'savingImages', //当前所有图片的隐藏域的名字
        maxImageNum: null, //最多传几张图片
        required: false, //是否必填
        validMsg: '必须至少上传一张图片', //验证失败时的提示信息
        onRemove : $.noop, //删除图片时的动作
        onBeforeDialogClose : $.noop, //关闭dialog前的动作
        onBeforeDialogOpen : $.noop, //打开dialog前的动作
        onDialogClose : $.noop, //关闭dialog时的动作
        onDialogOpen : $.noop,  //打开dialog时的动作
        beforeViewShow : $.noop,  //图片预览打开前的动作
        beforeViewClose : $.noop, //图片预览关闭前的动作
        afterViewClose : $.noop  //图片预览关闭后的动作
    }
    
//end closure    
})(jQuery);

/**
 * The second plugin. 
 * This plugin is the method for button what show loading when click this button. 
 * You can initialize all element into the loadingButton widget.
 * version: 0.3 (2012-08-06)
 */
(function($){// start closure
    $.fn.loadingButton = function(options, param){
        
        if (typeof options === 'string'){
            return $.fn.loadingButton.methods[options](this, param);
        }
        
        var opts = $.extend({}, $.fn.loadingButton.defaults, options);
        this.each(function(){
            var $this = $(this);
            $this.data('options',opts);
            var width = 0
            ,height = 0
            ,position
            ,marginLeft
            ,marginTop
            ,left=0
            ,top=0;
            if(opts.maskType == 'overButton'){
                width = $this.outerWidth();//计算宽度
                height = $this.outerHeight();//计算高度
                position = $this.position();//获得定位信息
                marginLeft = $this.css('margin-left').replace('px','');//获得margin-left
                marginTop = $this.css('margin-top').replace('px','');//获得margin-top
                left = parseFloat(position.left) + parseFloat(marginLeft) - parseFloat(opts.borderWidth);//计算left
                top = parseFloat(position.top) + parseFloat(marginTop) - parseFloat(opts.borderWidth);//计算top
            }else if(opts.maskType == 'overWindow'){
                width = Math.max(document.documentElement.clientWidth, document.body.clientWidth);//算当前window的宽度
                height = Math.max(document.documentElement.clientHeight, document.body.clientHeight);//计算当前window的高度
            }
            if(!$this.data('ifInitLdBtn')){
                $this.after('<div class="loadingMask" ></div>');
                $this.data('ifInitLdBtn', true);
            }
            
            var mask = $this.next();
            var maskCss = {//mask的样式
                position : 'absolute',
                border : opts.borderWidth+" "+opts.borderStyle+" "+opts.borderColor,
                height : height,
                width : width,
                left : left,
                top : top,
                background : 'url('+opts.backgroundImage+') no-repeat 50% 50% '+opts.backgroundColor,
                borderRadius : opts.borderRadius,
                opacity : opts.opacity,
                filter : 'alpha(opacity='+opts.opacity*100+')',
                display : 'none'
            };
            //            var maskMsgCss = {
            //                position : 'absolute',
            //                left : parseInt(width/2),
            //                top : parseInt(height/2)
            //            };
            mask.css(maskCss);
            //            $('.mask-msg').css(maskMsgCss);
            if(opts.autoStart){
                $this.click(function(){
                    opts.beforeMaskShow.call(this,$this);
                    mask.show();
                    opts.onMaskShow.call(this,$this);
                    if(opts.timeout > 0){
                        setTimeout(function(){
                            opts.beforeMaskHide.call(this,$this);
                            mask.hide();
                            opts.onMaskHide.call(this,$this);
                        }, opts.timeout);
                    }
                });
            }
        });
        
        return this;
    }
    
    $.fn.loadingButton.methods = {
        maskShow : function(jq){//显示loading
            jq.each(function(){
                $(this).next('div.loadingMask').show();
            });
            return jq;
        },
        maskHide : function(jq){//隐藏loading
            jq.each(function(){
                $(this).next('div.loadingMask').hide();
            });
            return jq;
        },
        resetMask : function(jq){//重新定位mask
            jq.each(function(){
                var opts = $(this).data('options');
                if(opts.maskType == 'overButton'){
                    var left = 0;
                    var top = 0;
                    var position = $(this).position();
                    var marginLeft = $(this).css('margin-left').replace('px','');
                    var marginTop = $(this).css('margin-top').replace('px','');
                    left = parseFloat(position.left) + parseFloat(marginLeft) - parseFloat(opts.borderWidth);
                    top = parseFloat(position.top) + parseFloat(marginTop) - parseFloat(opts.borderWidth);
                    $(this).next().css({
                        left : left,
                        top : top
                    });
                }
            });
            return jq;
        }
    }
    
    $.fn.loadingButton.defaults = {
        backgroundImage : '../../images/btn_loading.gif',   //图片地址
        backgroundColor : '#e0e0e0',                        //背景色
        opacity : 0.6,                                      //透明度
        borderRadius : 10,                                  //圆角角度
        borderWidth : 0,                                    //边框宽度 
        borderStyle : 'solid',                              //边框样式
        borderColor : '#cccccc',                            //边框颜色
        timeout : 1000,                                     //显示loading时间,如果设为小于0，则永远不隐藏loading
        beforeMaskShow : $.noop,                            //显示loading前的方法调用，返回false不显示loading
        beforeMaskHide : $.noop,                            //显示loading后的方法，返回false不隐藏loading，即loading不会消失
        onMaskShow : $.noop,                                //隐藏loading前的方法，返回false不隐藏loading
        onMaskHide : $.noop,                                //隐藏loading后的方法
        maskType : 'overButton',                            //mask类型，接受参数overButton(在按钮之上)、overWindow(在window之上)
        autoStart : true,                                   //是否自动弹出mask
        content : ''
    }
//end closure    
})(jQuery);